<template>
  <el-card shadow="hover">
    <el-descriptions
      class="margin-top"
      title="赠品"
      :column="3"
      :size="size"
      border
    />
    <div style="padding-bottom: 10px">
      <el-table v-loading="listLoading" :data="GiftList" show-summary>
        <el-table-column
          align="center"
          label="赠品ID"
          prop="OrderListID"
          show-overflow-tooltip
          width="70"
        />
        <el-table-column
          align="center"
          label="批准人"
          prop="Approver"
          show-overflow-tooltip
          :width="appoint ? '90' : ''"
        />
        <el-table-column
          align="center"
          label="赠品名称"
          prop="ProductName"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="赠品成本"
          prop="ProductCost"
          show-overflow-tooltip
          width="150"
        />
        <!-- <el-table-column
          align="center"
          label="计划服务期限"
          :width="appoint ? '230' : ''"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.PlanServiceStartDate }} 至 {{ row.PlanServiceEndDate }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="附件" width="150">
          <template #default="{ row }">
            <el-button
              v-if="JSON.parse(row.AttrFiles).length"
              type="success"
              size="small"
              @click="showAttrFiles(row)"
            >
              附件
            </el-button>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="showAttrFiles(row)"
            >
              附件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          :width="appoint ? '220' : '150'"
        >
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-button
                v-if="row.BindStoreID != 0"
                type="success"
                size="small"
                @click="giftEdit(row)"
              >
                补充详情
              </el-button>
              <el-button
                v-else
                type="danger"
                size="small"
                @click="giftEdit(row)"
              >
                补充详情
              </el-button>
              <!-- <el-button type="success" size="small" @click="giftEdit(row)">
              补充详情
            </el-button> -->
              <el-button
                v-if="OrderFlowState === 1"
                type="danger"
                size="small"
                @click="giftDelete(row)"
              >
                删除
              </el-button>
              <el-button
                v-if="appoint"
                :color="row.TaskSetState == 3 ? '#626aef' : ''"
                :type="
                  row.TaskSetState == 0
                    ? `danger`
                    : `${row.TaskSetState == 1 ? `warning` : `${row.TaskSetState == 2 ? `success` : `info`}`}`
                "
                size="small"
                @click="toAudit(row)"
              >
                审核约定任务
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="服务状态"
          show-overflow-tooltip
          width="200"
        >
          <template #default="{ row }">
            <div v-if="row.ServiceState == 0">待提单确认</div>
            <div v-if="row.ServiceState == 2">已提单</div>
            <div v-if="row.ServiceState == 3">已分单待运营</div>
            <div v-if="OrderType === 8 && row.ServiceState == 31">
              换店服务中
            </div>
            <div v-if="OrderType !== 8 && row.ServiceState == 31">
              运营服务中
            </div>
            <div v-if="row.ServiceState == 4">服务暂停中</div>
            <div v-if="row.ServiceState == 5">服务已终止</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="财务状态"
          show-overflow-tooltip
          width="200"
        >
          <template #default="{ row }">
            <div v-if="row.FankState == 1">正常</div>
            <div v-if="row.FankState == 0">已退款</div>
            <div v-if="row.FankState == -1">已退款</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <vab-query-form
      v-if="
        OrderFlowState === 1 ||
        actstaffpostid == 10 ||
        actstaffpostid == 11 ||
        actstaffpostid == 42
      "
      style="padding: 10px"
    >
      <!-- v-if="OrderFlowState < 4"  -->
      <vab-query-form-right-panel :span="24">
        <el-form ref="formRef" :model="GiftForm" :rules="rules">
          <el-space>
            <el-form-item label="批准人" prop="Approver">
              <el-input v-model="GiftForm.Approver" />
            </el-form-item>
            <el-form-item label="选择赠品" prop="SelectGift">
              <el-cascader
                v-model="GiftForm.SelectGift"
                :options="GiftOptions"
                :props="SelectProps"
                @change="handleSelectGift"
              />
            </el-form-item>
            <el-form-item label="成本金额" prop="ProductCost">
              <el-input v-model="GiftForm.ProductCost" disabled />
            </el-form-item>
            <el-form-item
              label="计划服务期限"
              prop="SeviceDates"
              style="width: 380px"
            >
              <DateSelect ref="DateSelectRef" @get-date="getDate" />

              <el-date-picker
                v-model="GiftForm.SeviceDates"
                unlink-panels
                type="daterange"
                start-placeholder="服务开始日期"
                end-placeholder="服务结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                :type="GiftForm?.AttrFiles?.length != 0 ? 'success' : 'primary'"
                @click="uploadFile"
              >
                附件
              </el-button>
            </el-form-item>

            <el-form-item>
              <el-button :icon="Search" type="primary" @click="saveGift">
                确认添加
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <trusteeship ref="trusteeshipRef" />
  </el-card>
  <!-- 添加的时候上传的附件 -->
  <el-dialog v-model="dialogOrderAttach" title="上传附件">
    <el-upload
      accept="image/png, image/jpeg"
      :file-list="GiftForm.AttrFiles"
      :multiple="true"
      action="https://api.sanjianke.com/common/Upload/upload?file=OrderAttrfile&type=image"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button @click="noUpFiles">清除</el-button> -->
        <el-button type="primary" @click="dialogOrderAttach = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 保存后点击上传附件 -->
  <el-dialog v-model="NewAttach" title="上传附件" @close="attachClose">
    <el-upload
      :file-list="clickGiftAttFiles"
      :multiple="true"
      action="https://api.sanjianke.com/common/Upload/upload?file=PaymentList&type=image"
      list-type="picture-card"
      :on-preview="NewPreview"
      :on-remove="NewRemove"
      :on-success="NewSuccess"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="upAttachment">保存</el-button>
      </div>
    </template>
    <!-- <el-dialog v-model="dialogVisible" top="3vh">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
        style="width: 100%"
      />
      <el-image-viewer
        v-if="dialogVisible"
        ref="imageViewer"
        :url-list="[dialogImageUrl]"
        />
    </el-dialog> -->
  </el-dialog>
  <el-image-viewer
    v-if="dialogVisible"
    :url-list="[dialogImageUrl]"
    @close="closeViewer"
  />
  <!-- 约定任务设置 -->
  <AgreedTaskEdit ref="AgreedTaskEditRef" @fetch-data="Update" />
</template>

<script>
  import AgreedTaskEdit from '@/views/business/components/AgreedTaskEdit'
  // import DateSelect from '/src/components/DateSelect.vue'
  import { GiftSelect, modProductFile } from '@/api/common'
  import { saveOrderGift, deleteGift } from '@/api/businessOrderCreate'
  import Trusteeship from '@/views/business/components/Trusteeship'

  export default defineComponent({
    name: 'GiftList',
    components: {
      // DateSelect,
      Trusteeship,
      AgreedTaskEdit,
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        actstaffpostid: 0,
        SelectProps: {
          expandTrigger: 'hover',
        },
        AgreedTaskEditRef: null,
        appoint: false,
        NewAttach: false,
        clickGiftID: 0,
        clickGiftAttFiles: [],
        dialogOrderAttach: false,
        dialogVisible: false,
        dialogImageUrl: '',
        OrderID: 0,
        DateSelectRef: null,
        trusteeshipRef: null,
        OrderFlowState: 1,
        listLoading: false,
        GiftOptions: [],
        formRef: null,
        editRef: null,
        GiftList: [],
        GiftForm: {
          OrderListID: 0,
          AttrFiles: [],
        },
        rules: {
          Approver: [
            {
              required: true,
              trigger: 'blur',
              message: '请添写赠品批准人',
            },
          ],
          SelectGift: [
            { required: true, trigger: 'change', message: '请选择赠品' },
          ],
          // SeviceDates: [
          //   {
          //     required: true,
          //     trigger: 'change',
          //     message: '请务必填写服务期限',
          //   },
          // ],
        },
        title: '',
      })
      const showList = (OrderInfo, list, check) => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const actstaffpost = JSON.parse(userInfo.StaffPostID)
        state.actstaffpostid = actstaffpost[0][1]
        if (check && check == 'appoint') {
          state.appoint = true
        } else {
          state.appoint = false
        }
        state.OrderID = OrderInfo.OrderID
        state.OrderFlowState = Math.abs(OrderInfo.OrderFlowState)
        state.GiftForm.OrderID = OrderInfo.OrderID
        state.GiftList = list
        state.GiftForm.AttrFiles = []
      }
      const closeViewer = () => {
        state.dialogImageUrl = ''
        state.dialogVisible = false
      }
      const giftEdit = (row) => {
        const businessClass = row.BusinessClassID
        switch (businessClass) {
          case 1:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 2:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 3:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 4:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 5:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            // if (row.ProductID == 63)
            //   state.domainRef.showEdit(row, state.OrderFlowState)
            // if (row.ProductID == 64)
            //   state.editRef.showEdit(row, state.OrderFlowState)
            break
          default:
            // state.giftRef.showEdit(row)
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
        }
      }

      const showAttrFiles = (row) => {
        console.log(row, '222')
        if (row) {
          state.clickGiftID = row.OrderListID
        }
        if (typeof row.AttrFiles == 'string') {
          state.clickGiftAttFiles = JSON.parse(row.AttrFiles)
        } else {
          state.clickGiftAttFiles = row.AttrFiles
        }
        state.NewAttach = true
      }

      const attachClose = () => {
        state.NewAttach = false
      }
      // 点击附件后保存附件
      const upAttachment = async () => {
        const dataMsg = {
          OrderListID: state.clickGiftID,
          AttFiles: state.clickGiftAttFiles,
        }
        await modProductFile(dataMsg)
        ElMessage({
          message: '保存成功',
          type: 'success',
        })
        attachClose()
        emit('fetch-data')
        console.log('点击附件后可以直接修改附件')
      }

      const giftDelete = (row) => {
        console.log(row)
        if (row.OrderListID) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deleteGift({
              OrderListID: row.OrderListID,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }
      const saveGift = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveOrderGift(state.GiftForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')

            // state.DateSelectRef.empty()
            state.GiftForm = {
              OrderListID: 0,
              AttrFiles: [],
            }
            emit('fetch-data')
          }
        })
      }
      // 选择赠品
      const handleSelectGift = (id) => {
        let giftMsg = state.GiftOptions
        for (let index = 0; index < id.length; index++) {
          const element = id[index]
          console.log(giftMsg, 'giftMsg')
          if (index != 0) {
            giftMsg = giftMsg.children.find((item) => {
              return item.value == element
            })
          } else {
            giftMsg = giftMsg.find((item) => {
              return item.value == element
            })
          }
        }

        state.GiftForm.ProductCost = giftMsg.cost

        console.log(giftMsg, '提取出来的')

        console.log(state.GiftForm, 'GiftOptions')
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { GiftOptions },
        } = await GiftSelect()
        state.GiftOptions = GiftOptions
        state.listLoading = false
      }
      const handlePictureCardPreview = (uploadFile) => {
        console.log('uploadFile', uploadFile)
        state.dialogImageUrl = uploadFile.url
        state.dialogVisible = true
      }
      const uploadFile = () => {
        state.dialogOrderAttach = true
      }

      const handleAvatarSuccess = (response) => {
        const data = {
          url: response.data.url,
        }
        state.GiftForm.AttrFiles.push(data)
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
      }
      onMounted(() => {
        fetchData()
      })
      const collectClose = () => {
        state.dialogCollect = false
        state.confirmMsg = {}
      }

      const handleRemove = (row) => {
        const index = state.GiftForm.AttrFiles.findIndex((fileItem) => {
          return fileItem.url === row.response.data.url
        })
        state.GiftForm.AttrFiles.splice(index, 1)
      }

      const NewRemove = () => {
        if (state.OrderFlowState != 1) {
          ElMessage({
            message: '不可删除',
            type: 'warning',
            plain: true,
          })
          state.NewAttach = false
          return
        }

        console.log(state.clickGiftAttFiles, '222')
      }

      const NewPreview = (uploadFile) => {
        state.dialogImageUrl = uploadFile.url
        state.dialogVisible = true
      }

      const NewSuccess = (response) => {
        const data = {
          url: response.data.url,
        }
        state.clickGiftAttFiles.push(data)
        console.log(state.clickGiftAttFiles, 'clickGiftAttFiles')

        ElMessage({
          message: '上传成功',
          type: 'success',
        })
      }
      const noUpFiles = () => {
        state.dialogOrderAttach = false
        state.GiftForm.AttrFiles = []
      }

      const toAudit = (row) => {
        console.log(row, 'rowrow')
        if (row.TaskSetState == 0) {
          ElMessageBox.confirm(
            '还未生成约定任务，是否直接生成？',
            '约定任务审核',
            {
              confirmButtonClass: 'confirmButtonClass',
              customClass: 'custom-message-box',
              confirmButtonText: '直接生成',
              cancelButtonText: '等待生成',
              type: 'warning',
            }
          )
            .then(() => {
              // 直接
              state.AgreedTaskEditRef.showEdit(row, 'direct')
            })
            .catch(() => {})
        } else if (row.TaskSetState == 3) {
          state.AgreedTaskEditRef.showEdit(row, 'direct')
        } else {
          state.AgreedTaskEditRef.showEdit(row, 'appoint')
        }
      }

      const Update = () => {
        emit('fetch-data')
      }

      // const getDate = (data) => {
      //   state.GiftForm.SeviceDates = data
      //   console.log(data, '子组件传过来的时间数组')
      // }
      return {
        ...toRefs(state),
        Update,
        toAudit,
        // getDate,
        noUpFiles,
        attachClose,
        NewSuccess,
        NewRemove,
        NewPreview,
        showList,
        upAttachment,
        handlePictureCardPreview,
        handleRemove,
        uploadFile,
        collectClose,
        handleAvatarSuccess,
        handleSelectGift,
        saveGift,
        giftEdit,
        giftDelete,
        showAttrFiles,
        closeViewer,
      }
    },
  })
</script>

<style>
  .confirmButtonClass {
    margin-right: 10px;
  }

  .custom-message-box .el-message-box__btns {
    display: flex;
    justify-content: flex-start;
    flex-direction: row-reverse;
  }
</style>
